/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hi.chyl.json;

import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import javax.swing.Icon;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.Timer;
import org.apache.commons.lang.StringUtils;
import org.netbeans.swing.tabcontrol.TabData;
import org.openide.util.Exceptions;

/**
 *
 * @author chench
 */
public class InterPanel extends JTabbedPane
{

    private boolean loading = false;
    private JsonPanel requestPanel;
    private JsonPanel responsepPanel;
    private MainView mainView;
    private TabData tabData;
    private Timer busyIconTimer;
    private Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    public File file;
    public Icon icon;

    public InterPanel(MainView mainView)
    {
        this.mainView = mainView;
        init();
    }
    
    public void setTabData(TabData tabData)
    {
        this.tabData = tabData;
        icon = tabData.getIcon();
    }

    private void init()
    {
        setTabPlacement(JTabbedPane.TOP);
        requestPanel = new JsonPanel();
        responsepPanel = new JsonPanel();
        addTab("请求报文", mainView.$icon("tab.icon"), requestPanel, "请输入发送到服务器的请求报文");
        addTab("返回报文", mainView.$icon("tab.icon2"), responsepPanel, "服务器返回的报文");

        for (int i = 0; i < busyIcons.length; i++)
        {
            busyIcons[i] = mainView.$icon("StatusBar.busyIcons[" + i + "]");
        }

        busyIconTimer = new Timer(30, new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                mainView.setTabIcon(tabData, busyIcons[busyIconIndex]);
            }
        });
        new DropTarget(requestPanel.getEditor(), DnDConstants.ACTION_COPY_OR_MOVE, mainView);
        new DropTarget(responsepPanel.getEditor(), DnDConstants.ACTION_COPY_OR_MOVE, mainView);
        
        SendKeyListner lst = new SendKeyListner();
        requestPanel.getEditor().addKeyListener(lst);
        responsepPanel.getEditor().addKeyListener(lst);
    }

    public void sendRequest(String url)
    {
        if (loading)
        {
            JOptionPane.showMessageDialog(null, "正在加载，请稍候！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        loading = true;

        String data = getRequestData();
        if (StringUtils.isEmpty(data))
        {
            JOptionPane.showMessageDialog(null, "请输入请求报文！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        boolean isJson = requestPanel.parseJson();
        if (!isJson)
            return ;
        
        
        final RequestWorker worker = new RequestWorker(url, data);
        worker.addPropertyChangeListener(new PropertyChangeListener()
        {

            public void propertyChange(PropertyChangeEvent evt)
            {
                if ("state".equals(evt.getPropertyName()) && "DONE".equals(evt.getNewValue().toString()))
                {
                    if (!loading)
                        return;
                    loading = false;
                    
                    busyIconTimer.stop();
                    mainView.setTabIcon(tabData, icon);
                    try
                    {
                        String resp = worker.get();
                        updateResponseTab(resp);
                    } catch (Exception ex)
                    {
                        Exceptions.printStackTrace(ex);
                        JOptionPane.showMessageDialog(null, ex.getLocalizedMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });
        busyIconTimer.start();
        worker.execute();
    }

    public void stopRequest()
    {
        loading = false;
        busyIconTimer.stop();
        mainView.setTabIcon(tabData, icon);
    }

    private void updateResponseTab(String resp)
    {
        getResponseEditor().setText(resp);
        responsepPanel.formatJson();
        setSelectedIndex(1);
    }

    public JsonPanel getRequestPanel()
    {
        return requestPanel;
    }

    public JsonPanel getResponsePanel()
    {
        return responsepPanel;
    }

    public JTextArea getRequestEditor()
    {
        return requestPanel.getEditor();
    }

    public JTextArea getResponseEditor()
    {
        return responsepPanel.getEditor();
    }

    public String getRequestData()
    {
        return requestPanel.getEditor().getText();
    }

    public String getResponseData()
    {
        return responsepPanel.getEditor().getText();
    }
    
    class SendKeyListner extends KeyAdapter
    {
        @Override
        public void keyTyped(KeyEvent e)
        {
            if (e.getKeyCode() == KeyEvent.VK_ENTER && e.isControlDown())
            {
                mainView.sendRequest();
            }
        }
    }
}
